package com.yiyihealth.cherriesadmin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.service.impl.BaseServiceImpl;
import com.yiyihealth.cherriesadmin.core.utils.JKTUtil;
import com.yiyihealth.cherriesadmin.core.webservice.MainServiceImplPortType;
import com.yiyihealth.cherriesadmin.core.webservice.MainServiceImplPortTypeService;
import com.yiyihealth.cherriesadmin.mapper.*;
import com.yiyihealth.cherriesadmin.model.*;

import com.yiyihealth.cherriesadmin.model.his.DictDepart;
import com.yiyihealth.cherriesadmin.model.jkt.JThealth;
import com.yiyihealth.cherriesadmin.model.jkt.JktFunc10001;
import com.yiyihealth.cherriesadmin.model.jkt.JktFunc10002;
import com.yiyihealth.cherriesadmin.model.wrapper.PubDepartmentsWrapper;
import com.yiyihealth.cherriesadmin.service.PubDepartmentsService;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.yiyihealth.cherriesadmin.core.utils.JKTUtil.sortMap;

/**
 * 执行科室科室(PubDepartments)表服务实现类
 *
 * @author chen
 * @since 2020-09-14 20:03:30
 */
@Service
@CacheConfig(cacheNames = "departments")
public class PubDepartmentsServiceImpl extends BaseServiceImpl<PubDepartments, PubDepartmentsWrapper, Long> implements PubDepartmentsService {
    @Resource
    private PubDepartmentsMapper pubDepartmentsMapper;
    @Resource
    private PubDoctorMapper doctorMapper;
    @Resource
    private OrdSchedulingMapper schedulingMapper;
    @Resource
    private PubDictionaryMapper dictionaryMapper;
    @Resource
    private PubHospitalMapper hospitalMapper;
    @Resource
    private RedisTemplate<Object, Object> redisCacheTemplate;

    @Resource
    private JktFunc10002 jktFunc10002;
    @Resource
    private JThealth jThealth;

    @Autowired
    private void setEntityMapper() {
        super.setEntityMapper(pubDepartmentsMapper);
    }

    @Override
    public List<PubDepartments> selectListByDepNameStatus(@Param("depName") String depName, @Param("status") String status) {
        return null;
    }

    @Override
    public List<PubDepartments> selectListByDepFatherId(@Param("status")String status, @Param("hospitalId")Long hospitalId, @Param("depFatherId")Long depFatherId) {
        return null;
    }

    @Override
    public List<PubDepartmentsWrapper> selectListWrapperByDepFatherId(@Param("status")String status, @Param("hospitalId")Long hospitalId, @Param("depFatherId")Long depFatherId) {
        return null;
    }

    @Override
    public List<PubDepartments> selectListByHospitalId(@Param("hospitalId")Long hospitalId, @Param("status")String status) {
        return null;
    }

    @Scheduled(cron = "0 0 22 ? * *")
    @Override
    public synchronized void ExtractHisData() throws Exception {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("status","0");
        List<PubHospital> hospitalList = hospitalMapper.selectList(paramMap);
        String tokenStr = "";
        String httpMsg  ;
        for (PubHospital hospital:hospitalList) {
            if (StrUtil.isBlank(hospital.getHosRegionalCode())){
                continue;
            }
            httpMsg  = "更新成功！";
            String json = JSONUtil.parseObj("{}").toString();
            tokenStr = "";
            try {
                tokenStr = HttpUtil.post(hospital.getHosRegionalCode()+"/dictDepart/select_list", json);
            } catch (Exception e) {
                httpMsg = "调用"+ hospital.getHosName()+"中间数据处理服务失败,请确认服务地址："+hospital.getHosRegionalCode()+"是否正常！";
            }
            paramMap.clear();
            paramMap.put("hospitalId",hospital.getId());
            List<PubDepartments> departmentsList = pubDepartmentsMapper.selectList(paramMap);
            if (httpMsg.equals("更新成功！")){
                HttpResult httpResult = JSONUtil.toBean(tokenStr,HttpResult.class);
                List<DictDepart> dictDepartList = JSONUtil.toList((JSONArray) httpResult.getData(),DictDepart.class);
                for (DictDepart dictDepart:dictDepartList){
                    if (!hospital.getId().toString().equals(dictDepart.getHospitalId())){
                        throw new Exception("中间服务地址错误，当前机构编码："+hospital.getId()+" 请确认服务地址是否正确？");
                    }
                    String redisKey = "departments:"+dictDepart.getHospitalId()+":"+dictDepart.getKeshibm();
                    if (hospital.getId().toString().equals("57171")){
                        dictDepart.setKeshibm("D"+dictDepart.getKeshibm());
                    }else if (hospital.getId().toString().equals("57172")){
                        dictDepart.setKeshibm("H"+dictDepart.getKeshibm());
                    }else if (hospital.getId().toString().equals("57170")){
                        dictDepart.setKeshibm(""+dictDepart.getKeshibm());
                    }
                    List<PubDepartments> departmentsTempList = departmentsList.stream().filter(departments ->departments.getHospitalId().toString().equals(dictDepart.getHospitalId())  && departments.getDepInternalCode().equals(dictDepart.getKeshibm())).collect(Collectors.toList());
                    PubDepartments departments = new PubDepartments();

                    if (CollectionUtils.isEmpty(departmentsTempList)){
                        departments = createBean(dictDepart,departments);
                        departments.setUpdateStatus(httpMsg);
                        pubDepartmentsMapper.insert(departments);
                    }else {
                        departments=departmentsTempList.get(0);
                        if (departments.getId().equals(86000100L)){
                            System.out.println(departments.getId().toString());
                        }
                        if (dictDepart.getKeshibm().contains("029")){
                            System.out.println(dictDepart.getKeshibm());
                        }
                        //判断是否同步数据
                        if (Optional.ofNullable(departments.getSync()).isPresent() && departments.getSync().equals("1")){
                            if (!dictDepart.getZhuxiaobz().equals(1)){
                                departmentsList.removeAll(departmentsTempList);
                            }
                            continue;
                        }
                        departments = createBean(dictDepart,departments);
                        departments.setUpdateStatus(httpMsg);
                        pubDepartmentsMapper.updateByPrimaryKeySelective(departments);
                    }

                    if (redisCacheTemplate.hasKey(redisKey)){
                        redisCacheTemplate.delete(redisKey);
                    }
                    departmentsList.removeAll(departmentsTempList);
                    redisCacheTemplate.opsForValue().set(redisKey,departments);
                    redisCacheTemplate.opsForValue().set("departments:"+departments.getHospitalId()+":"+departments.getId(),departments);
                }
                for (PubDepartments departments:departmentsList){
                    departments.setStatus("1");
                    pubDepartmentsMapper.updateByPrimaryKeySelective(departments);
                }
            }else {
                for (PubDepartments departments:departmentsList){
                    departments.setUpdateStatus(httpMsg);
                    pubDepartmentsMapper.updateByPrimaryKeySelective(departments);
                }
            }

        }
    }

    @Override
    public List<PubDictionary> selectListByDepFather(Long dicType, Long hospitalId) {
        Map<String,Object> map = new HashMap<>();
        map.put("dicType",dicType);
        List<PubDictionary> dictionaryList=dictionaryMapper.selectList(map);
        List<PubDictionary> dictionaries = new ArrayList<>();
        for (PubDictionary dictionary:dictionaryList){
            map.clear();
            map.put("depFatherId",dictionary.getId());
            map.put("hospitalId",hospitalId);
            List<PubDepartments> departmentsList = pubDepartmentsMapper.selectList(map);
            if (!CollectionUtils.isEmpty(departmentsList)){
                dictionary.setDepartmentsList(departmentsList);
                dictionaries.add(dictionary);
            }
        }
        return dictionaries;
    }


    @Override
    public List<PubDepartments> selectOption(Map map) {
        List<PubDepartments> list=pubDepartmentsMapper.selectList(map);
        List<PubDepartments> list1=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            if (list.get(i).getDepClinic().equals("1")&&list.get(i).getStatus().equals("0")){
                list1.add(list.get(i));
            }
        }


        return list1;
    }

    @Override
    public void jktUpload(Long hospitalId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("depClinic","1");
        map.put("status","0");
        if (!hospitalId.toString().equals("0")){
            map.put("hospitalId",hospitalId);
        }


        List<PubDepartments> departmentsWrapperList = pubDepartmentsMapper.selectList(map);
   /*     List<PubDepartments> departmentsWrapperList2=new ArrayList<>();
        for (PubDepartments departments:departmentsWrapperList){
            if(!"".equals(departments.getDepFatherId()) && departments.getDepFatherId()!=null){
                departmentsWrapperList2.add(departments);
            }
        }
*/

        for (PubDepartments departments:departmentsWrapperList){
            if (departments.getDepFatherId()<1){
                continue;
            }
            try {
                PubDictionary heath;
                PubDictionary dictionary = dictionaryMapper.selectByPrimaryKey(departments.getDepFatherId());
                if (departments.getDepName().equals("失眠调理专科")){
                    System.out.println(departments);
                }
                if (Optional.ofNullable(dictionary).isPresent()){
                    if (dictionary.getDicCode().equals("99")){
                        heath = dictionaryMapper.selectByPrimaryKey(148L);
                        departments.setStatus("1");
                    }
                    heath = dictionaryMapper.selectByPrimaryKey(dictionary.getHealthyId());
                }else {
                    heath = dictionaryMapper.selectByPrimaryKey(148L);
                    departments.setStatus("1");
                }
                jktFunc10002.setDeptTypeCode(heath.getDicCode());
                jktFunc10002.setDeptTypeName(heath.getDicName());

                jktFunc10002.setDeptId(departments.getId().toString());
                if (departments.getDepInternalCode().startsWith("H")){
                    jktFunc10002.setDeptName(departments.getDepName()+"(和平)");
                }else if (departments.getDepInternalCode().startsWith("D")){
                    jktFunc10002.setDeptName(departments.getDepName()+"(凤起)");
                }else {
                    jktFunc10002.setDeptName(departments.getDepName()+"(丰潭)");
                }

                jktFunc10002.setDeptDesc("暂无");
                jktFunc10002.setDeptState(departments.getStatus());
                jktFunc10002.setDeptTypeBelong(heath.getDicName());


                List<JSON> jktFun10002InList = new ArrayList<>();
                sortMap(BeanUtil.beanToMap(jktFunc10002));
                jktFun10002InList.add(JSONUtil.parse(jktFunc10002));
                Map<String,Object> FuncMap =  new HashMap<>();
                FuncMap.put("list",jktFun10002InList);
                JKTUtil.jThealthPost("10002",FuncMap, jThealth);
            }catch (Exception e){
                throw new Exception("上传科室信息："+departments.getDepName()+e.getMessage());
            }
        }
    }

    @Override
    public List<PubDepartmentsWrapper> selectListByDepFatherId(Long depFatherId, Long hospitalId) {
        Map<String,Object> map = new HashMap<>();
        map.put("status",0);
        map.put("depFatherId",depFatherId);
        map.put("hospitalId",hospitalId);
        List<PubDepartmentsWrapper> departmentsList =pubDepartmentsMapper.selectListWrapper(map);
        for (PubDepartmentsWrapper departments:departmentsList){
            map.clear();
            map.put("status",0);
            map.put("depId",departments.getId());
            map.put("hospitalId",hospitalId);
            List<OrdScheduling> ordSchedulingList = schedulingMapper.selectList(map);
            List<PubDoctor> doctorList = new ArrayList<>();
            for (OrdScheduling scheduling:ordSchedulingList){
                PubDoctor pubDoctor = doctorMapper.selectByPrimaryKey(scheduling.getDoctorId());
                List<PubDoctor> doctors = doctorList.stream().filter(pubDoctorWrapper -> pubDoctorWrapper.getId().toString().equals(pubDoctor.getId().toString())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(doctors)){
                    doctorList.add(pubDoctor);
                }
            }
            doctorList = doctorList.stream().distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(doctorList)){
                departments.setDoctorNum(doctorList.size());
            }
        }
        return departmentsList.stream().filter(pubDepartmentsWrapper -> pubDepartmentsWrapper.getStatus().equals("0")).sorted(Comparator.comparing(PubDepartments::getDepInternalCode)).collect(Collectors.toList());
    }

    PubDepartments createBean(DictDepart dictDepart,PubDepartments departments) throws Exception {
        try {
            departments.setDepName(dictDepart.getKeshimc());
            departments.setDepAlias(dictDepart.getKeshimc());
            departments.setChinaSpell(dictDepart.getPinyinma());
            departments.setDepInternalCode(dictDepart.getKeshibm());

            departments.setStatus(dictDepart.getZhuxiaobz().toString());
            departments.setSync("0");
        }catch (Exception e){
            throw new Exception(departments.toString()+"");
        }
        return departments;
    }

    @Override
    public PubDepartments updateByPrimaryKeySelective(PubDepartments record) {
        if (Optional.ofNullable(record.getDepFatherId()).isPresent()){
            if (record.getDepFatherId().toString().equals("4513")){
                record.setDepFatherId(0L);
                record.setDepCode("");
                record.setDepClinic("1");
                record.setDepCode("  ");
            }else{
                record.setDepClinic("1");
                record.setDepCode("50");
            }
        }
        return super.updateByPrimaryKeySelective(record);
    }
}
